﻿using System;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;


namespace SKN.SPMOSS
{
    public static class Webpart
    {
        public static void AddWebpartAudience (SPWeb web, string pageName, string wpTitle, Guid audienceId)
        {
            SPLimitedWebPartManager wpManager = web.GetLimitedWebPartManager(pageName, PersonalizationScope.Shared);
            SPLimitedWebPartCollection wpCol = wpManager.WebParts;

            foreach (System.Web.UI.WebControls.WebParts.WebPart webp in wpCol)
            {
                //Check for the webpart title, if matches , apply audience
                if (string.Equals(webp.Title,wpTitle,StringComparison.InvariantCultureIgnoreCase))
                {
                    webp.AuthorizationFilter = audienceId.ToString() + ";;;;";
                    wpManager.SaveChanges(webp);
                    break;
                }
            }
        }
    }
}
